package com.five.admin.controller;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.five.admin.dto.UserQueryDto;
import com.five.admin.dto.UserStatusDto;
import com.five.admin.dto.UserUpdateDto;
import com.five.admin.server.UserService;
import com.five.core.result.Result;
import com.five.pojo.entity.User;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @PostMapping("/list")
    public Result list(@RequestBody UserQueryDto userQueryDto) {
        Page<User> userPage = userService.userQuery(userQueryDto);
        return Result.buildSuccess(userPage.getTotal(), userPage.getRecords());
    }

    @GetMapping("/find/{id}")
    public Result find(@PathVariable Integer id) {
        User user = userService.getById(id);
        return Result.buildSuccess(user);
    }

    @PostMapping("/toggleStatus")
    public Result toggleStatus(@RequestBody UserStatusDto userStatusDto) {
        boolean update = userService.update(new LambdaUpdateWrapper<User>()
                .eq(User::getId, userStatusDto.getId())
                .set(User::getStatus, userStatusDto.getStatus()));
        return update ? Result.buildSuccess() : Result.buildFail("更新失败");
    }

    @PostMapping("/update")
    public Result update(@RequestBody UserUpdateDto userUpdateDto) {
        User user = User.builder()
                .id(userUpdateDto.getId())
                .username(userUpdateDto.getUsername())
                .phone(userUpdateDto.getPhone())
                .email(userUpdateDto.getEmail())
                .status(userUpdateDto.getStatus())
                .build();
        boolean update = userService.updateById(user);
        return update ? Result.buildSuccess() : Result.buildFail("更新失败");
    }

    @PostMapping("/resetPassword")
    public Result resetPassword(@RequestBody UserUpdateDto userUpdateDto){
        return userService.resetPassword(userUpdateDto) ? Result.buildSuccess() : Result.buildFail("重置密码失败");
    }
}
